﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using HCMServices.BUS;
using HCMServices.DTO;
using HCMServices.GUI;
using System.IO.IsolatedStorage;
using System.IO;

namespace HCMServices
{
    /// <summary>
    /// Main Page for application
    /// </summary>
    public partial class MainPage : PhoneApplicationPage
    {        
        public GUI.Service PassingService { get; set; }
        public DataDTO PassingData { get; set; }
        private SearchEngine searchEngine = null;
        private List<HardDataDTO> hardDataDTOResult = null;
        private string _LastSearchString = "";

        /// <summary>
        /// Initialize All Component in this function
        /// </summary>
        public MainPage()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ShowServiceDetails(sender);
        }
        private int _SelectedIndex = -1;
        private List<DetailServiceDTO> _SelectedDetailServiceDTO = new List<DetailServiceDTO>();
        private List<Service> _ListServiceToDetail = new List<Service>();
        private List<DataDTO> _ListDataDTOToDetail = new List<DataDTO>();

        private void ShowServiceDetails(object sender)
        {
            //// xử lí khi chọn một địa điểm trong list
            //ItemCollection a = resultListBox.Items;
            //int e = resultListBox.SelectedIndex;
            Button sdf = sender as Button;
            PassingService = (GUI.Service)sdf.DataContext;
            for (int i = 0; i < _ListServiceToDetail.Count; i++)
            {
                if (((GUI.Service)_ListServiceToDetail[i]).Data == PassingService.Data)
                {
                    this._SelectedIndex = i;
                    i = 2147483646;
                }
            }
            PassingData = this._ListDataDTOToDetail[this._SelectedIndex];
            this._SelectedDetailServiceDTO = this.searchEngine.GetListDetaiServiceDTO(this._ListDataDTOToDetail[this._SelectedIndex]);            
            this.NavigationService.Navigate(new Uri("/GUI/PlaceDetailsPage.xaml", UriKind.Relative));
        }

        internal void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            this.listBoxSuggest.Visibility = Visibility.Collapsed;
            GetSearchResult();
        }

        private List<DataDTO> _DataDTOResult = new List<DataDTO>();

        private void GetSearchResult()
        {
            if (this.searchTextBox.Text != string.Empty)
            {
                if (this._LastSearchString != this.searchTextBox.Text)
                {
                    ////tim tat ca dich vu theo tu khoa nhap vao(DataDTO)
                    _DataDTOResult = this.searchEngine.SearchForDataDTOResult(this.searchTextBox.Text);

                    ////tim tat ca dich vu theo tu khoa nhap vao(HardDataDTO)
                    //hardDataDTOResult = this.searchEngine.SearchForHardDataDTOResult(this.searchTextBox.Text);
                    hardDataDTOResult = this.searchEngine.ReturnHardDataFromDataDTO(_DataDTOResult);

                    List<GUI.Service> listService = new List<GUI.Service>();
                    listService = MakeListServiceFromHardData(this.hardDataDTOResult);
                    if (0 == listService.Count)
                        this.statusTextBlock.Text = "Không tìm thấy kết quả phù hợp.";
                    else
                        this.statusTextBlock.Text = "Tìm thấy " + listService.Count.ToString() + " kết quả phù hợp.";
                    resultListBox.ItemsSource = listService;

                    this._ListServiceToDetail = listService;
                    this._ListDataDTOToDetail = _DataDTOResult;

                    this._LastSearchString = this.searchTextBox.Text;

                    this.ResetGUI();
                    //List<DetailServiceDTO> temp = this.searchEngine.GetListDetaiServiceDTO(dataDTOResult);

                    //test searchnearby
                    //this.SearchNearbyFrom(_DataDTOResult[0]);

                }
            }
        }

        private List<GUI.Service> MakeListServiceFromHardData(List<HardDataDTO> input)
        {
            List<GUI.Service> temp = new List<GUI.Service>();
            for (int i = 0; i < input.Count; i++)
            {
                temp.Add(new GUI.Service(input[i]));
            }
            return temp;
        }

        private void ResetGUI()
        {
            this.costList.SelectedIndex = -1;
            this.costSelector.Content = "Tất cả giá";

            this.CostStyleForSort.SelectedIndex = -1;
            this.SortByCost.Content = "Sắp xếp theo giá";

            this.serviceList.SelectedIndex = -1;
            this.serviceSelector.Content = "Tất cả dịch vụ";

            this.streetList.SelectedIndex = -1;
            this.streetSelector.Content = "Tất cả đường";
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            GUI.PlaceDetailsPage placeDetailPageInstance = e.Content as GUI.PlaceDetailsPage;
            if (placeDetailPageInstance != null)
            {
                placeDetailPageInstance.Service = PassingService;
                placeDetailPageInstance.Data = this.PassingData;
                placeDetailPageInstance.ListDeltailService = this._SelectedDetailServiceDTO;
            }
        }

        private void StreetSelector_Click(object sender, RoutedEventArgs e)
        {
            ////lay tat ca cac duong trong ket qua tra ve o tren
            if (this.streetList.Visibility == System.Windows.Visibility.Visible)
            {
                this.streetList.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {

                this.streetList.ItemsSource = this.searchEngine.GetFilterInfo(_DataDTOResult, SearchEngine._FILTER_INFO_DUONG);
                this.streetList.Visibility = System.Windows.Visibility.Visible;

            }
        }

        private void ServiceSelector_Click(object sender, RoutedEventArgs e)
        {
            ////lay tat ca cac dich vu trong ket qua tra ve o tren
            if (this.serviceList.Visibility == System.Windows.Visibility.Visible)
            {
                this.serviceList.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {

                this.serviceList.ItemsSource = this.searchEngine.GetFilterInfo(_DataDTOResult, SearchEngine._FILTER_INFO_DICHVU);
                this.serviceList.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void ServiceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ListBox)sender).SelectedIndex >= 0)
            {
                this.serviceList.Visibility = Visibility.Collapsed;
                if (e.AddedItems.Count > 0)
                    this.serviceSelector.Content = e.AddedItems[0].ToString();
                else this.serviceSelector.Content = "Tất cả dịch vụ";
                Filter();
            }
        }

        private void StreetList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ListBox)sender).SelectedIndex >= 0)
            {
                this.streetList.Visibility = Visibility.Collapsed;
                if (e.AddedItems.Count > 0)
                    this.streetSelector.Content = e.AddedItems[0].ToString();
                else this.streetSelector.Content = "Tất cả đường";
                Filter();
            }
        }

        private void Filter()
        {
            if (hardDataDTOResult != null)
            {
                List<GUI.Service> listService = new List<GUI.Service>();
                this._ListDataDTOToDetail = new List<DataDTO>();
                this._ListServiceToDetail = new List<Service>();
                for (int i = 0; i < hardDataDTOResult.Count; i++)
                {
                    if (1 > serviceList.SelectedIndex ||
                        (hardDataDTOResult[i].ServiceName == serviceList.SelectedItem.ToString()
                        && serviceList.SelectedIndex != 0))
                        if (1 > streetList.SelectedIndex ||
                            (hardDataDTOResult[i].StreetName == streetList.SelectedItem.ToString()
                            && streetList.SelectedIndex != 0))
                            if (1 > costList.SelectedIndex ||
                            (this.searchEngine.ListDetailServiceDTO[i] != null && this.searchEngine.ListDetailServiceDTO[i].Cost == int.Parse(costList.SelectedItem.ToString())
                            && costList.SelectedIndex != 0))
                            {
                                listService.Add(new GUI.Service(hardDataDTOResult[i]));
                                this._ListServiceToDetail.Add(new GUI.Service(hardDataDTOResult[i]));
                                this._ListDataDTOToDetail.Add(this._DataDTOResult[i]);
                            }
                }
                if (0 == listService.Count)
                    this.statusTextBlock.Text = "Không tìm thấy kết quả phù hợp.";
                else
                    this.statusTextBlock.Text = "Tìm thấy " + listService.Count.ToString() + " kết quả phù hợp.";
                resultListBox.ItemsSource = listService;
            }
        }

        private void PivotItem_Unloaded(object sender, RoutedEventArgs e)
        {
            this.streetList.Visibility = Visibility.Collapsed;
            this.serviceList.Visibility = Visibility.Collapsed;
        }

        private bool _enableSearchNearbyPlace = false;

        public bool EnableSearchNearbyPlace
        {
            get { return _enableSearchNearbyPlace; }
            set { _enableSearchNearbyPlace = value; }
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (null == this.searchEngine)
            {
                this.loadingTextBlock.Visibility = System.Windows.Visibility.Visible;
                this.resultListBox.Visibility = System.Windows.Visibility.Collapsed;
                this.searchEngine = new SearchEngine();
            }

            this.loadingTextBlock.Visibility = System.Windows.Visibility.Collapsed;
            this.resultListBox.Visibility = System.Windows.Visibility.Visible;

            if (EnableSearchNearbyPlace)
            {
                SearchNearbyFrom(this.PassingData);
                EnableSearchNearbyPlace = false;
            }
        }

        private void PivotItem_LostFocus(object sender, RoutedEventArgs e)
        {
            this.streetList.Visibility = Visibility.Collapsed;
            this.serviceList.Visibility = Visibility.Collapsed;
            this.costList.Visibility = Visibility.Collapsed;
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.streetList.Visibility = Visibility.Collapsed;
            this.serviceList.Visibility = Visibility.Collapsed;
            this.costList.Visibility = Visibility.Collapsed;
        }

        private bool _Numberic = true;

        private void searchTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            //if (this.listBoxSuggest.Visibility == Visibility.Collapsed)
            //{
            //if (!this._IsChooseFromSuggest)
            //{
            //    this.listBoxSuggest.Items.Clear();
            //    List<string> result = this.searchEngine.GetSuggest(this.searchTextBox.Text);
            //    foreach (string temp in result)
            //    {
            //        this.listBoxSuggest.Items.Add(temp);
            //    }
            //    this.listBoxSuggest.Visibility = Visibility.Visible;
            //}
            //else
            //{
            //    this._IsChooseFromSuggest = false;
            //}
            if (this._Numberic)
            {
                if (!_IsChooseFromSuggest)
                {
                   
                    List<string> result = this.searchEngine.GetSuggest(this.searchTextBox.Text);
                    if (result.Count > 0)
                    {
                        //this.listBoxSuggest.Items.Clear();
                        //foreach (string temp in result)
                        //{
                        //    this.listBoxSuggest.Items.Add(temp);
                        //}
                        this.listBoxSuggest.ItemsSource = result;
                        this.listBoxSuggest.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        //this.listBoxSuggest.Items.Clear();
                        List<String> resultString = this.searchEngine.GetAutoCorrect(this.searchTextBox.Text);
                        if (resultString != null)
                        {
                            this.listBoxSuggest.ItemsSource = resultString;
                            this.listBoxSuggest.Visibility = Visibility.Visible;
                        }
                    }
                }
                else
                {
                    _IsChooseFromSuggest = false;
                }
                this._Numberic = false;
            }
            else
                this._Numberic = true;

            //}
        }

        private bool _IsChooseFromSuggest = false;

        private void listBoxSuggest_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.searchTextBox.Text = this.listBoxSuggest.SelectedItems[0].ToString();
            this.listBoxSuggest.Visibility = Visibility.Collapsed;
            this._IsChooseFromSuggest = true;
        }

        private void costSelector_Click(object sender, RoutedEventArgs e)
        {
            if (this.costList.Visibility == System.Windows.Visibility.Visible)
            {
                this.costList.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {

                this.costList.ItemsSource = this.searchEngine.GetFilterInfo(_DataDTOResult, SearchEngine._FILTER_INFO_GIA);
                this.costList.Visibility = System.Windows.Visibility.Visible;
                
            }
        }

        private void costList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ListBox)sender).SelectedIndex >= 0)
            {
                this.costList.Visibility = Visibility.Collapsed;
                if (e.AddedItems.Count > 0)
                    this.costSelector.Content = e.AddedItems[0].ToString();
                else this.costSelector.Content = "Tất cả giá";
                Filter();
            }
        }

        private void SortByCost_Click(object sender, RoutedEventArgs e)
        {
            if(this.CostStyleForSort.Visibility == Visibility.Visible)
            {
                this.CostStyleForSort.Visibility = Visibility.Collapsed;
            }
            else
                this.CostStyleForSort.Visibility = Visibility.Visible;
        }

        private void CostStyleForSort_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ListBox)sender).SelectedIndex >= 0)
            {

                SortByCost.Content = ((ListBoxItem)CostStyleForSort.Items[((ListBox)sender).SelectedIndex]).Content;

                _ListServiceToDetail = this.SortResultByCost(((ListBox)sender).SelectedIndex);

                //no ko chiu update ngay
                resultListBox.ItemsSource = _ListServiceToDetail;


                CostStyleForSort.Visibility = Visibility.Collapsed;

            }
        }

        private List<Service> SortResultByCost(int p)
        {
            List<Service> result = new List<Service>(_ListServiceToDetail);
            //result = _ListServiceToDetail;
            switch (p)
            {
                case 0:
                    {
                        //tang dan
                        List<DetailServiceDTO> listDetail = new List<DetailServiceDTO>();
                        listDetail = this.searchEngine.GetListDetaiServiceDTO(_ListDataDTOToDetail);
                        for (int i = listDetail.Count - 1; i >= 0; i--)
                        {
                            int costI;
                            if (listDetail[i] != null)
                                costI = listDetail[i].Cost;
                            else
                                costI = 0;
                            for (int j = listDetail.Count - 1; j >= 0; j--)
                            {
                                int costJ = 0;
                                if (listDetail[j] == null)
                                    costJ = 0;
                                else
                                    costJ = listDetail[j].Cost;

                                if (costI > costJ)
                                {
                                    Service temp = result[i];
                                    result[i] = result[j];
                                    result[j] = temp;

                                    DetailServiceDTO tempDTO = listDetail[i];
                                    listDetail[i] = listDetail[j];
                                    listDetail[j] = tempDTO;

                                    DataDTO tempDataDTO = _ListDataDTOToDetail[i];
                                    _ListDataDTOToDetail[i] = _ListDataDTOToDetail[j];
                                    _ListDataDTOToDetail[j] = tempDataDTO;
                                }
                            }
                        }
                        break;
                    }

                case 1:
                    {
                        //giam dan

                        List<DetailServiceDTO> listDetail = new List<DetailServiceDTO>();
                        listDetail = this.searchEngine.GetListDetaiServiceDTO(_ListDataDTOToDetail);
                        for (int i = 0; i < listDetail.Count; i++)
                        {
                            int costI;
                            if (listDetail[i] != null)
                                costI = listDetail[i].Cost;
                            else
                                costI = 0;
                            for (int j = 0; j < listDetail.Count; j++)
                            {
                                int costJ = 0;
                                if (listDetail[j] == null)
                                    costJ = 0;
                                else
                                    costJ = listDetail[j].Cost;

                                if (costI > costJ)
                                {
                                    Service temp = result[i];
                                    result[i] = result[j];
                                    result[j] = temp;

                                    DetailServiceDTO tempDTO = listDetail[i];
                                    listDetail[i] = listDetail[j];
                                    listDetail[j] = tempDTO;

                                    DataDTO tempDataDTO = _ListDataDTOToDetail[i];
                                    _ListDataDTOToDetail[i] = _ListDataDTOToDetail[j];
                                    _ListDataDTOToDetail[j] = tempDataDTO;
                                }
                            }
                        }

                        break;
                    }

                default:
                    break;
            }
            return result;
        }

        private void update_button_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/GUI/UpdatePage.xaml", UriKind.Relative));
        }

        public void SearchNearbyFrom(DataDTO input)
        {
            this._ListDataDTOToDetail = this.searchEngine.SearchNearby(input);
            this.hardDataDTOResult = this.searchEngine.ReturnHardDataFromDataDTO(_ListDataDTOToDetail);
            this._ListServiceToDetail = this.MakeListServiceFromHardData(hardDataDTOResult);

            this.resultListBox.ItemsSource = _ListServiceToDetail;
        }

        private void listBoxSuggest_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
        }

    }
    public enum GoogleTileTypes
    {
        Hybrid,
        Physical,
        Street,
        Satellite,
        WaterOverlay
    }
    public class GoogleTile : Microsoft.Phone.Controls.Maps.TileSource
    {
        private int _server;
        private char _mapmode;
        private GoogleTileTypes _tiletypes;

        public GoogleTileTypes TileTypes
        {
            get { return _tiletypes; }
            set
            {
                _tiletypes = value;
                MapMode = MapModeConverter(value);
            }
        }

        public char MapMode
        {
            get { return _mapmode; }
            set { _mapmode = value; }
        }

        public int Server
        {
            get { return _server; }
            set { _server = value; }
        }

        public GoogleTile()
        {
            UriFormat = @"http://mt{0}.google.com/vt/lyrs={1}&z={2}&x={3}&y={4}";
            Server = 0;
        }

        public override Uri GetUri(int x, int y, int zoomLevel)
        {
            if (zoomLevel > 0)
            {
                var Url = string.Format(UriFormat, Server, MapMode, zoomLevel, x, y);
                return new Uri(Url);
            }
            return null;
        }

        private char MapModeConverter(GoogleTileTypes tiletype)
        {
            switch (tiletype)
            {
                case GoogleTileTypes.Hybrid:
                    {
                        return 'y';
                    }
                case GoogleTileTypes.Physical:
                    {
                        return 't';
                    }
                case GoogleTileTypes.Satellite:
                    {
                        return 's';
                    }
                case GoogleTileTypes.Street:
                    {
                        return 'm';
                    }
                case GoogleTileTypes.WaterOverlay:
                    {
                        return 'r';
                    }
            }
            return ' ';
        }
    }
}